12 7
There is a space in front of the "7" which cannot be part of a number.
trim()
Method
Leading and trailing spaces can be removed from a string by using the
trim()
method of class String.
For example,
" 143 ".trim()
is
"143"
This is useful in correcting some slightly defective input files. Here is the sample program with this enhancement:
import java.io.*; class AddTwo { public static void main ( String[] args ) throws IOException { int numberA, numberB; String line; BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) ); System.out.println("Enter first number:"); line = stdin.readLine(); numberA = Integer.parseInt( line.trim() ); System.out.println("Enter second number:"); line = stdin.readLine(); numberB = Integer.parseInt( line.trim() ); System.out.println( "Sum: " + (numberA + numberB) ); } }
This will not solve all problems, however. Here is a highly defective input file:
12 seven